package com.yc.bos.web.realm;

import com.yc.bos.dao.IFunctionDao;
import com.yc.bos.dao.IUserDao;
import com.yc.bos.model.Function;
import com.yc.bos.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class BOSRealm extends AuthorizingRealm{
    /**
     * 权限-与角色权关
     * @param principal
     * @return
     */
    @Autowired
    private IFunctionDao functionDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //拿到用户
        User loginUser= (User) principal.getPrimaryPrincipal();
        List<Function> functions=null;

        if(loginUser.getUsername().equals("admin")){
            functions=functionDao.findAll();
        }else {
            functions=functionDao.findMenuByUserId(loginUser.getId());
        }

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
      for(Function function:functions){
          info.addStringPermission(function.getCode());
      }
        return info;
    }
    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
@Autowired
private IUserDao userDao;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("AuthenticationInfo.......");
        UsernamePasswordToken upToken= (UsernamePasswordToken) token;
        String username=upToken.getUsername();
        User dbuser=userDao.findByUsername(username);
        if(dbuser!=null){
            /*
             * Object principal, 把数据库查询的对象
             * Object credentials,证书：写密码自动验证，查询出来的密码
             * String realmName,当前的类名
             */
            //返回AuthenticationInfo对象,【这个对象会自动验证密码】
            SimpleAuthenticationInfo info=
                    new SimpleAuthenticationInfo(dbuser,
                            dbuser.getPassword(),
                            this.getClass().getSimpleName());
            return info;

        }

        return null;
    }
}
